import axios from 'axios';
import { apiBaseUrl } from '@/config/api';

// 创建 axios 实例
const api = axios.create({
  baseURL: apiBaseUrl,
  timeout: 5000
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 可以在这里添加请求头，如 token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    config.headers['Content-Type'] = 'application/json';
    console.log("请求拦截器", config);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    // 统一处理响应数据
    if (response.data && response.data.code === 200) {
      console.log(response.data);
      return response.data;
    } else {
      return Promise.reject(response.data.message);
    }
  },
  error => {
    // 统一处理错误响应
    // console.error('请求出错:', error);
    return Promise.reject(error);
  }
);

// 定义 API 接口
export const createUser = (data) => api.post('/api/admin/users', data);
export const deleteUser = (username) => api.delete(`/api/admin/users?username=${username}`);
export const getAllUsers = (token) => api.get('/api/admin/users/ls', { headers: { Authorization: `Bearer ${token}` } });
export const login = (data) => api.post('/api/admin/users/login', data);